import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home/Home.vue'
import Login from '../views/login.vue'
import No from '../views/404.vue'
import canUserAccess  from "../request/canUserAccess.js"

const routes = [
  {
    path: '/',
    redirect: '/home',
  },
  {
    path: '/home',
    redirect: '/home/survey',
    component: Home,
    children: [
      {
        path: 'survey',
        component: () => import(/* webpackChunkName: "survey" */ '@/views/Home/_MySurvey.vue'),
      },
      {
        path: 'recycle-bin',
        component: () => import(/* webpackChunkName: "survey" */ '@/views/Home/_RecycleBin.vue'),
      },
    ],
  },
  {
    name: 'login',
    path: '/login',
    component: Login,
  },
  {
    path: '/new-survey/',
    component: () => import(/* webpackChunkName: "new-survey" */ '../views/new-survey/new-survey.vue'),
  },
  {
    path: '/show-statistics/:id',
    component: () => import(/* webpackChunkName: "show-statistics" */ '../views/show-statistics/show-statistics.vue'),
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'Default',
    component: No,
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

router.beforeEach(async (to, from) => {
  try {
    if (to.name === 'login') {
      return
    }
    const canAccess = await canUserAccess()
    if (!canAccess) return '/login'
  } catch (e) {
    console.error(e.message)
  }

})

export default router
